package org.dg.dgimg.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.dg.dgimg.entity.User;
import org.dg.dgimg.service.IUserService;
import org.dg.dgimg.utils.EmailUtils;
import org.dg.dgimg.utils.JWTUtils;
import org.dg.dgimg.utils.RedisUtils;
import org.dg.dgimg.utils.RestBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.UUID;

import static org.dg.dgimg.utils.JWTUtils.resolveJwt;

/**
 *  User前端控制器
 *
 * @author DG
 * @since 2024-06-25
 */
@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    IUserService userService;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    EmailUtils emailUtils;

    @GetMapping(value = "/login", produces = "application/json;charset=UTF-8")
    public String userLogin(String mail, String password){
        if(mail == null || mail.isEmpty() || password == null || password.isEmpty()) return JSONObject.toJSONString(RestBean.failure(403,"不能为空!"));
        if(userService.selectUserByMailAndPassword(mail,password) == null) return JSONObject.toJSONString(RestBean.failure(404,"登录失败!"));

        //颁发JWT令牌，将令牌中的player部分放到redis中储存
        String uuid = String.valueOf(UUID.randomUUID());
        String JWT = JWTUtils.createJwt(uuid);

        //redis储存方法为拿到JWT令牌中的player部分值当为key，value储存user对象值
        User userJson = userService.selectUserByMailAndPassword(mail,password);
        String user = JSON.toJSONString(userService.selectUserByMailAndPassword(mail,password));
        long timeout = 7 * 24 * 60 * 60; //7天时间
        redisUtils.set(uuid,user,timeout);

        userJson.setJWT(JWT);
        userJson.setUserPassword(null);

        return JSONObject.toJSONString(RestBean.success(userJson));
    }

    @PostMapping(value = "/register", produces = "application/json;charset=UTF-8")
    public String userRegister(User user){
        if (user==null) return JSONObject.toJSONString(RestBean.failure(404,"传入参数不能为空!"));
        try {
            String code = redisUtils.getkey(user.getUserMail());
            if (code == null) return JSONObject.toJSONString(RestBean.failure(403,"验证码过期!"));
            if (!code.equals(user.getCode()))return JSONObject.toJSONString(RestBean.failure(404,"验证码错误!"));
            //注册账号
            if (userService.insertUser(user) == 0) return JSONObject.toJSONString(RestBean.failure(404,"注册失败!"));

            return JSONObject.toJSONString(RestBean.success("注册成功!"));
        } catch (Exception e) {
            log.error("UserController userRegister error"+e.getMessage());
            return JSONObject.toJSONString(RestBean.failure(500));
        }

    }

    @GetMapping(value = "/email", produces = "application/json;charset=UTF-8")
    public String userGetEmail(String mail){
        if (mail==null||mail.isEmpty())return JSONObject.toJSONString(RestBean.failure(404,"获取的邮箱不能为空！"));
        try {
            //检查邮箱是否存在
            if (userService.selectUserCountByMail(mail) > 0) return JSONObject.toJSONString(RestBean.failure(403,"邮箱已经注册!"));
            String num = redisUtils.getkey(mail);
            if (num != null) return JSONObject.toJSONString(RestBean.failure(404,"请不要重复请求!"));
            Map<String,String> map = emailUtils.sendEmail(mail);
            String code = map.get("code");
            String email = map.get("email");
            long timeout = 3 * 60; // 3分钟的秒数
            redisUtils.set(email,code,timeout);
            return JSONObject.toJSONString(RestBean.success());
        } catch (Exception e) {
            log.error("UserController userGetEmail error"+e.getMessage());
            return JSONObject.toJSONString(RestBean.failure(500));
        }
    }

    @GetMapping(value = "/token/login", produces = "application/json;charset=UTF-8")
    public String userGetToken(String token){
        if (token == null || token.isEmpty()) return JSONObject.toJSONString(RestBean.failure(403,"请先登录!"));
        String userId = resolveJwt(token);
        User user = JSONObject.parseObject(redisUtils.getkey(userId),User.class);
        if(user!=null) {
            user.setUserPassword(null);
            return JSONObject.toJSONString(RestBean.success(user));
        }return JSONObject.toJSONString(RestBean.failure(403,"重新登录!"));
    }
}
